package dominia.widgets;

import java.util.Iterator;
import java.util.LinkedList;

import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import dominia.SWTMain;

public class LogWindow extends SingletonDialog implements Appender {
	protected String		name;
	protected Layout		layout;

	protected LinkedList<String>	buffer;
	protected int			maxlines = 200;

	protected LogWindow()
	{
		super("Log Window");
		
		buffer = new LinkedList<String>();
		name = "logwindow";
		layout = new PatternLayout("[%d{HH:mm:ss}] %p: %m%n");
	}

	public static LogWindow getInstance()
	{
		return (LogWindow)SingletonDialog.getInstance(LogWindow.class);
	}

	public Object open()
	{
		Object dummy = null;
		Shell parent = getParent();
		Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shell.setText(getText());
		shell.setSize(640, 480);
		
		Color white = new Color(parent.getDisplay(), 255, 255, 255);

		StyledText log = new StyledText(shell, SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL);
		log.setBackground(white);
		log.setBounds(3, 3, 625, 445);
		Iterator it = buffer.iterator();
		while(it.hasNext())
			log.append((String)it.next());

		shell.open();
		Display display = parent.getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}

		return dummy;
	}

	public void addFilter(Filter arg0)
	{
		
	}

	public void clearFilters()
	{
		
	}

	public void close()
	{
		buffer.clear();
	}

	public void doAppend(LoggingEvent ev)
	{
		if (buffer.size() == maxlines)
			buffer.remove();

		buffer.add(layout.format(ev));
	}

	public ErrorHandler getErrorHandler()
	{
		return null;
	}

	public Filter getFilter()
	{
		return null;
	}

	public Layout getLayout()
	{
		return null;
	}

	public String getName()
	{
		return this.name;
	}

	public boolean requiresLayout()
	{
		return false;
	}

	public void setErrorHandler(ErrorHandler arg0)
	{
		
	}

	public void setLayout(Layout arg0)
	{	
	}

	public void setName(String arg0)
	{
		this.name = arg0;
	}
}